const app = getApp()
import {
    getToken,
    getAuth
} from './account'
const uploadUrl = app.globalData.host + '/data/api.auth.member/upload'


function uploadPic(file) {
    return new Promise(async (resolve, reject) => {
        const token = await getToken()
        wx.uploadFile({
            url: uploadUrl,
            filePath: file,
            name: 'image',
            formData: {},
            header: {
                "Content-Type": "application/x-www-form-urlencoded",
                'token': token
            },
            success: function (res) {
                wx.hideToast();
                var data = JSON.parse(res.data);
                if (data.code === 1) {
                    resolve(data.info)
                } else if (data.info === '请求令牌不能为空！') { //无token
                    wx.clearStorageSync()
                    getAuth()
                } else if (data.info === 'Undefined index: caliance_club_id') { //token过期
                    wx.showToast({
                        title: '登录已失效',
                        icon: 'none',
                        duration: 2000,
                        success(res) {
                            wx.clearStorageSync()
                        }
                    })
                } else {
                    wx.showModal({
                        title: '错误提示',
                        content: '上传图片失败',
                        showCancel: false,
                        success: function (res) {}
                    })
                }
            },
            fail: function (res) {
                wx.showModal({
                    title: '错误提示',
                    content: '上传图片失败',
                    showCancel: false,
                    success: function (res) {}
                })
            },
        });
    })
}
export function upload(count = 1) {
    return new Promise(async (resolve, reject) => {
        wx.chooseImage({
            count: count, //最多可以选择的图片总数
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                var tempFilePaths = res.tempFilePaths;
                const imgArr = tempFilePaths.map(async (item, index) => {
                    //启动上传等待中...
                    wx.showToast({
                        title: `正在上传第${index+1}张`,
                        icon: 'loading',
                        mask: true,
                        duration: 10000
                    })
                    let uploadFileResult = await uploadPic(item)
                    return uploadFileResult
                })
                Promise.all(imgArr).then((result) => {
                    wx.hideLoading();
                    wx.showToast({
                        title: '上传成功',
                        icon: "none",
                        duration: 2000
                    });
                    console.log("上传图片结果", result)
                    resolve(result)
                })
            }
        });
    })
}

export function uploadVideo() {
    return new Promise(async (resolve, reject) => {
        const token = await getToken()
        wx.chooseVideo({
            maxDuration: 30,
            success: function (res) {
                var tempFilePath = res.tempFilePath;
                //启动上传等待中...
                wx.showToast({
                    title: '正在上传...',
                    icon: 'loading',
                    mask: true,
                    duration: 10000
                })
                wx.uploadFile({
                    url: uploadUrl,
                    filePath: tempFilePath,
                    name: 'image',
                    formData: {},
                    header: {
                        "Content-Type": "application/x-www-form-urlencoded",
                        'token': token
                    },
                    success: function (res) {
                        wx.hideToast();
                        var data = JSON.parse(res.data);
                        //服务器返回格式: { "Catalog": "testFolder", "FileName": "1.jpg", "Url": "https://test.com/1.jpg" }
                        if (data.code === 1) {
                            resolve(data.info)
                        } else if (data.info === '请求令牌不能为空！') { //无token
                            wx.clearStorageSync()
                            getAuth()
                        } else if (data.info === 'Undefined index: caliance_club_id') { //token过期
                            wx.showToast({
                                title: '登录已失效',
                                icon: 'none',
                                duration: 2000,
                                success(res) {
                                    wx.clearStorageSync()
                                }
                            })
                        } else {
                            wx.showModal({
                                title: '错误提示',
                                content: '上传视频失败',
                                showCancel: false,
                                success: function (res) {}
                            })
                        }
                    },
                    fail: function (res) {
                        console.log(res, 'fail')
                        wx.hideToast();
                        wx.showModal({
                            title: '错误提示',
                            content: '上传视频失败',
                            showCancel: false,
                            success: function (res) {}
                        })
                    },
                });
            }
        });
    })
}

export function uploadfile(url, params) {
    return new Promise(async (resolve, reject) => {
        const token = await getToken()
        wx.chooseMessageFile({
            count: 1,
            type: 'file',
            extension: ['xls', 'xlsx'],
            maxDuration: 30,
            success: function (res) {
                var tempFilePath = res.tempFiles[0].path;
                //启动上传等待中...
                wx.showToast({
                    title: '正在上传...',
                    icon: 'loading',
                    mask: true,
                    duration: 10000
                })
                wx.uploadFile({
                    url: app.globalData.host + url,
                    filePath: tempFilePath,
                    name: 'groupexcel',
                    formData: params,
                    header: {
                        "Content-Type": "application/x-www-form-urlencoded",
                        'token': token
                    },
                    success: function (res) {
                        wx.hideToast();
                        console.log(res);
                        var data = JSON.parse(res.data);
                        //服务器返回格式: { "Catalog": "testFolder", "FileName": "1.jpg", "Url": "https://test.com/1.jpg" }
                        console.log(data);
                        if (data.code === 1) {
                            resolve(data.info)
                        } else if (data.info === '请求令牌不能为空！') { //无token
                            wx.clearStorageSync()
                            getAuth()
                        } else if (data.info === 'Undefined index: caliance_club_id') { //token过期
                            wx.showToast({
                                title: '登录已失效',
                                icon: 'none',
                                duration: 2000,
                                success(res) {
                                    wx.clearStorageSync()
                                }
                            })
                        } else {
                            console.log(res)
                            wx.showModal({
                                title: '错误提示',
                                content: '上传文件失败 \r\n' + data.info,
                                showCancel: false,
                                success: function (res) {}
                            })
                        }
                    },
                    fail: function (res) {
                        console.log(res)
                        wx.hideToast();
                        wx.showModal({
                            title: '错误提示',
                            content: '上传文件失败',
                            showCancel: false,
                            success: function (res) {}
                        })
                    },
                });
            }
        });
    })
}


async function uploadImagealioss(tempFiles, filesize, match_id, uploadtype, fnsuccuse) {

    var that = this;
    var player_id = app.globalData.userInfo.player_id;


    let policyUrl = app.globalData.getOssInfo;
    wx.request({
        url: policyUrl, //获取oss签名
        method: "POST",
        data: {
            player_id: player_id,
            openID: app.globalData.userInfo.openid,
            filesize: filesize
        },
        success: function (res) {

            console.log(res);
            if (res.statusCode == 200) {
                if (res.data.errorcode.code != 'ok') {
                    wx.showToast({
                        title: res.data.errorcode.message,
                        icon: 'error',
                        duration: 2000
                    })
                    return;
                }
                var succindex = 0;
                var urls = [];
                for (var index = 0; index < tempFiles.length; index++) {
                    let post = res.data.data;
                    console.log(post);
                    var tempFile = tempFiles[index].path;
                    var size = tempFiles[index].size;
                    let arrayfileopaths = tempFile.split("/");
                    let filename = arrayfileopaths[arrayfileopaths.length - 1];
                    let n = tempFile.lastIndexOf('.');
                    let type = tempFile.substring(n);

                    let foot1 = 'x-oss-process=image/resize,w_1080,h_1920,m_fill/watermark,type_d3F5LXplbmhlaQ,size_38,text_'
                    const aliyunFileKey = post.dir + 'players_' + player_id + '/' + Date.parse(new Date()) / 1000 + filename;
                    let showUrl = null;
                    wx.showLoading({
                        title: '图片上传中'
                    });
                    wx.uploadFile({
                        url: 'https://' +  post.host, //上传到OSS
                        filePath: tempFile,
                        name: 'file',
                        formData: {
                            'name': filename,
                            'key': aliyunFileKey,
                            'OSSAccessKeyId': post.accessid,
                            'policy': post.policy,
                            'signature': post.signature,
                            'success_action_status': '200',
                        },
                        success: function (ossres) {
                            console.log("阿里云", ossres.statusCode)
                            console.log(res);
                            if (ossres.statusCode == 200) {

                                showUrl = 'https://'+  post.host + '/' + aliyunFileKey
                                var urldata = {
                                    type: type,
                                    player_id: app.globalData.userInfo.player_id,
                                    match_id: match_id,
                                    file: showUrl,
                                    filesize: size
                                };

                                console.log(urldata);
                                return new Promise(async (resolve, reject) => {
                                    wx.request({
                                        url: app.globalData.interfaceuploadimage,
                                        data: urldata,
                                        method: 'POST',
                                        header: {
                                            "Content-Type": "application/x-www-form-urlencoded"
                                        },
                                        success(fileres) {
                                            console.log(fileres);
                                            if (fileres.data.errorcode.code == "ok") {
                                                // resolve(res.data);
                                                if (fileres.data) {
                                                    succindex++;
                                                    urls.push(fileres.data.data);
                                                    console.log(urls)
                                                    if (succindex >= tempFiles.length) {
                                                        //resolve(urls);
                                                        fnsuccuse(urls);
                                                    }
                                                }

                                            } else {
                                                wx.showToast({
                                                    title: fileres.data.errorcode.message,
                                                    icon: 'error',
                                                    duration: 1200
                                                })

                                                return;
                                            }
                                        },
                                        fail(fileres) {
                                            console.log(fileres);
                                            wx.showToast({
                                                title: fileres.errMsg,
                                                icon: 'error'
                                            })
                                            reject(fileres);
                                        },
                                        complete() {
                                            wx.hideLoading();

                                        }
                                    })
                                })



                            } else {
                                wx.showToast({
                                    title: fileres.errorcode.message,
                                    icon: 'none',
                                    duration: 1200
                                })

                            }
                        },
                        fail: function (ossres) {
                            console.log(ossres);
                            wx.showToast({
                                title: '上传失败！',
                                icon: 'none',
                                duration: 1200
                            })


                        },
                        complete: function () {
                            wx.hideLoading();
                        }
                    })
                }
               
            } else {

            }
        }
    })

}

function uploadfileinfo(file, match_id, filesize, type) {
    var that = this;


}


export function uploadUserInfoImagealioss(Avatar, fnsuccuse) {

  var that = this;
  var player_id = app.globalData.userInfo.player_id;
  var user_id = app.globalData.userInfo.userID;

  let policyUrl = app.globalData.getOssInfo;
  wx.request({
      url: policyUrl, //获取oss签名
      method: "POST",
      data: {
          player_id: player_id,
          openID: app.globalData.userInfo.openid,
      },
      success: function (res) {

          console.log(res);
          if (res.statusCode == 200) {
              if (res.data.errorcode.code != 'ok') {
                  wx.showToast({
                      title: res.data.errorcode.message,
                      icon: 'error',
                      duration: 2000
                  })
                  return;
              }
              var succindex = 0;
              var urls = [];
              
                  let post = res.data.data;
                  console.log(post);
                  var tempFile = Avatar;
                console.log(Avatar);
                  let arrayfileopaths = tempFile.split("/");
                  let filename = arrayfileopaths[arrayfileopaths.length - 1];
                  let n = tempFile.lastIndexOf('.');
                  let type = tempFile.substring(n);

                  let foot1 = '?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto';// 用来视频封面的
                  const aliyunFileKey = post.dir + 'players_' + player_id + '/' + Date.parse(new Date()) / 1000 + filename;
                  let showUrl = null;
                  wx.showLoading({
                      title: '图片上传中'
                  });
                  wx.uploadFile({
                      url: 'https://' +  post.host, //上传到OSS
                      filePath: tempFile,
                      name: 'file',
                      formData: {
                          'name': filename,
                          'key': aliyunFileKey,
                          'OSSAccessKeyId': post.accessid,
                          'policy': post.policy,
                          'signature': post.signature,
                          'success_action_status': '200',
                      },
                      success: function (ossres) {
                          console.log("阿里云", ossres.statusCode)
                          console.log(res);
                          if (ossres.statusCode == 200) {

                              showUrl = 'https://'+  post.host + '/' + aliyunFileKey
                              var urldata = {
                                  type:-1,
                                  player_id: app.globalData.userInfo.player_id,
                                  avatarUrl: showUrl,
                                  user_id:user_id
                              };

                              console.log(urldata);
                              return new Promise(async (resolve, reject) => {
                                  app.updateUserinfo(urldata,fnsuccuse, reject);
                              })
                          } else {
                              wx.showToast({
                                  title: fileres.errorcode.message,
                                  icon: 'none',
                                  duration: 1200
                              })

                          }
                      },
                      fail: function (ossres) {
                          console.log(ossres);
                          wx.showToast({
                              title: '上传失败！',
                              icon: 'none',
                              duration: 1200
                          })


                      },
                      complete: function () {
                          wx.hideLoading();
                      }
                  })
              
             
          } else {

          }
      }
  })

}

export function uploadImage(match_id, type, fnsuccuse) {

    var that = this;
    wx.chooseImage({
        count: 9, //选择多少个图片
        sourceType: ['album', 'camera'], //视频来源相册和相机都可以
        //maxDuration: 15,	//相机拍摄最大时长为30S
        camera: 'back', //默认摄像头是后置摄像头
        success(res) {
            console.log(res);
            // 判断上传文件格式
            let tempFilePaths = res.tempFilePath;
            let tempFiles = res.tempFiles;

            var sizetotal = 0;
            var isoversize = false;
            var MAX_size = 5 * 1000 * 1000;
            tempFiles.forEach(item => {
                sizetotal += item.size;
                if (item.size > MAX_size) {
                    isoversize = true;
                }
            });
            if (isoversize) {
                wx.showToast({
                    title: '单个文件不能超过5M',
                    duration: 2000,
                    icon: 'error'
                })
                return;
            }
            uploadImagealioss(tempFiles, sizetotal, match_id, type, fnsuccuse);
        },
        fail(res) {
            console.log(res);
            if (res.errMsg == "chooseVideo:fail cancel") {

            } else {

            }
        }
    })
}